<?php

namespace app\middleware;

use app\manager\RedisInstance;
use app\model\RegisterModel;
use app\model\UserModel;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;
use think\facade\Session;
use think\response\Json;



/**todo
 * 统一返回格式分装
 * 新增拦截器完成统一异常捕获
 * */
class CheckToken3
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
       // echo Request::url();exit();
        $cookie = $_COOKIE;
        //print_r($cookie);exit();
        $urls = [
            '/login/login',
            'register'
        ];
        //exit('来饿了');
        if (in_array(Request::url(),$urls)){
            return $next($request);
        } else {
            if (empty($_SESSION['uid'])) {
                throw new Exception('未登录1');
            }
            $adminId='6';
            $where=[];
            if ($_SESSION['uid'] ==$adminId){
                out('1');
                $where=[];
            }else{
                $where=[
                    'u.user_id'=>$_SESSION['uid']
                ];
            }
            // 管理员账号Id
            $adminId='6';

            if ($_SESSION['uid'] ==$adminId){
                //超级管理员
                $data= Db::table('menu')->field('route')->select()->toArray();
            }else{
                //普通用户
                $data = Db::table('admin_user_role')
                    ->alias('u')
                    ->where('u.user_id',$_SESSION['uid'])
                    ->join('menu m','u.menu_id = m.id')
                    ->field('m.route')
                    ->select()->toArray();
            }
            //out($data);
            $arr = array_column($data, 'route');
            //exit(Request::url());
            if (in_array(Request::url(),$arr)){
                session_start();
                $_SESSION['menu']=$arr;
                return $next($request);
            }
            else{
                throw new \Exception('没有权限');
            }


        }
    }
}
